<template>
    <a-modal
        :title="!currRow ? '添加用户' : '编辑用户'"
        :visible="isShowModal"
        width="40%"
        :footer="null"
        dialogClass="custom-modal"
        :maskClosable="false"
        @cancel="handleCancel"
    >
        <a-spin :spinning="loadingRoleOptions">
            <a-form-model
                :model="form"
                ref="form"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                :rules="rules"
                :colon="false"
                class="m-form-model"
            >
                <a-row :gutter="10">
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="用户名" prop="userName">
                            <a-input
                                autoComplete="off"
                                placeholder="请输入用户名"
                                v-model.trim="form.userName"
                                allowClear
                                :disabled="!!currRow"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="真实姓名">
                            <a-input placeholder="请输入真实姓名" v-model.trim="form.realName" allowClear />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="密码" prop="password">
                            <a-input-password
                                autoComplete="new-password"
                                placeholder="请输入密码"
                                v-model.trim="form.password"
                                allowClear
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16" style="padding: 0">
                        <a-form-model-item label="确认密码" prop="surePassword">
                            <a-input-password
                                autoComplete="new-password"
                                placeholder="请再次输入密码"
                                v-model.trim="form.surePassword"
                                allowClear
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16" style="padding: 0">
                        <a-form-model-item label="联系电话" prop="mobile">
                            <a-input
                                placeholder="请输入联系电话"
                                v-model.trim="form.mobile"
                                allowClear
                                :disabled="currRow && !currRow.isChangeMobile"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="角色" prop="roleId">
                            <a-select
                                placeholder="请选择角色"
                                v-model="form.roleId"
                                allowClear
                                :loading="loadingRoleOptions"
                            >
                                <a-select-option v-for="(item, index) in roleList" :key="index" :value="item.id">
                                    {{ item.roleName }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="所属区域" prop="areaId" class="modal-tree-select">
                            <a-tree-select
                                :load-data="onLoadData"
                                v-model="form.areaId"
                                style="width: 100%"
                                :tree-data="treeData"
                                :replace-fields="{ label: 'name', value: 'id', children: 'children' }"
                                :dropdownStyle="dropdownStyle"
                                :treeCheckStrictly="true"
                                :show-checked-strategy="SHOW_PARENT"
                                placeholder="请选择区域"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24" class="mb16">
                        <a-form-model-item label="所属单位" prop="jobId" class="modal-tree-select">
                            <a-input placeholder="请输入所属单位" v-model.trim="form.orgName" allowClear />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="24">
                        <a-button type="primary" class="fr" @click="handleOk" :loading="confirmLoading">确定</a-button>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-spin>
    </a-modal>
</template>
<script>
import { FormModel, TreeSelect } from 'ant-design-vue'
import { usersApi, areaApi } from '../../../../common/api/setting'
import { validatorTel } from '../../../../utils/validation'
import { getTreeData } from '@/utils/methods'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
const rules = {
    userType: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
    roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    areaId: [{ required: true, message: '请选择区域', trigger: 'blur' }],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
    mobile: [
        {
            required: true,
            trigger: 'blur',
            message: '请输入正确的手机号码格式',
            validator: validatorTel,
        },
    ],
}
export default {
    data() {
        return {
            SHOW_PARENT,
            loadingRoleOptions: false,
            confirmLoading: false,
            dropdownStyle: {
                height: '200px',
            },
            form: {
                userName: '',
                realName: '',
                password: '',
                surePassword: '',
                mobile: '',
                roleId: null,
                areaId: null,
                orgName: '', //所属单位
                remarks: '', //备注
                // userType: 1,
            },
            rules: {
                ...rules,
                surePassword: [
                    {
                        required: true,
                        trigger: 'blur',
                        validator: (rule, value, callback) => {
                            if (!value) {
                                return callback(new Error('请再次输入密码'))
                            }
                            if (value !== this.form.password) {
                                return callback(new Error('两次密码不匹配'))
                            }
                            return callback()
                        },
                    },
                ],
            },
            treeData: [],
        }
    },
    components: {
        AFormModelItem: FormModel.Item,
    },
    props: {
        isShowModal: {
            required: true,
            type: Boolean,
        },
        currRow: {
            required: false,
            type: [Object, undefined],
        },
        roleList: {
            required: false,
            type: Array,
        },
        areaInitOptions: {
            required: false,
            type: Array,
            default: () => [],
        },
        treeSelectedAreaId: {
            required: false,
            type: String,
        },
    },
    watch: {
        isShowModal: {
            immediate: true,
            handler: function (isShowModal) {
                if (isShowModal) {
                    let id = this.$store.state.userInfo.areaId
                    this.getTreeNodes({ id })
                    this.beforeShowModal()
                } else {
                    this.$refs.form && this.$refs.form.resetFields()
                }
            },
        },
    },
    beforeDestroy() {
        this.$refs.form && this.$refs.form.resetFields()
    },
    methods: {
        beforeShowModal() {
            if (this.currRow) {
                // 编辑
                let { password, roleId, userName, realName, mobile, userType, areaId } = this.currRow

                Object.assign(this.form, {
                    password,
                    roleId: roleId || undefined,
                    userName,
                    realName,
                    mobile,
                    areaId,
                    surePassword: password,
                    userType,
                })
                console.log(this.form)
                this.form = { ...this.form }
            }
        },
        async save() {
            let { password, roleId, userName, realName, mobile, areaId, userType } = this.form
            const apiType = this.currRow ? 'edit' : 'add'
            this.confirmLoading = true

            let res
            try {
                res = await usersApi[apiType]({
                    password,
                    roleId,
                    userName,
                    realName,
                    mobile,
                    areaId,
                    id: this.currRow && this.currRow.id,
                    enterpriseId: this.treeSelectedAreaId,
                    userType,
                })
                if (res.code == 200) {
                    this.$message.success('操作成功')
                    this.$emit('update:isShowModal', false)
                    this.$emit('updateData')
                } else {
                    this.$message.error(res.message)
                }
            } catch (e) {
                console.log(e)
            }
            this.confirmLoading = false
        },
        async handleOk() {
            console.log(this.form)
            this.$refs.form.validate(async valid => {
                if (valid) {
                    this.save()
                } else {
                    return false
                }
            })
        },
        handleCancel() {
            this.$emit('update:isShowModal', false)
        },
        onLoadData(treeNode) {
            // expandedTreeNodeKeys更新,treeData找不到对应展开key数据会触发此方法,并且会依次触发展开
            console.log('onLoadTreeData')
            return new Promise((resolve, reject) => {
                const currNode = treeNode.dataRef
                console.log(currNode, 'currNode')
                if (treeNode.dataRef.children) {
                    resolve()
                    return
                }
                console.log(treeNode, 'treeNode')
                // 浅拷贝
                this.getTreeNodes(currNode)
                    .then(() => {
                        resolve()
                    })
                    .catch(() => {
                        // 报错则收起当前展开节点
                        const currExpandNodeIdIndex = this.expandedTreeNodeKeys.indexOf(currNode.id)
                        if (currExpandNodeIdIndex > -1) {
                            this.expandedTreeNodeKeys.splice(currExpandNodeIdIndex, 1)
                        }
                        resolve() // 必须resolve
                    })
            })
        },
        async getTreeNodes(currNode = {}) {
            await areaApi.children({ id: currNode.id }).then(res => {
                if (res.code == 200) {
                    let areaArr = [res.data]
                    if (this.treeData.length === 0) {
                        this.treeData = areaArr
                        return
                    }
                    currNode.children = [...res.data.children]
                    this.treeData = [...this.treeData]
                }
            })
        },
    },
}
</script>
<style scoped lang="scss">
/deep/ .modal-tree-select .ant-select {
    min-height: 32px !important;
    height: unset !important;
}
.supervise-search-icon {
    position: absolute;
    z-index: 1;
    right: 10px;
    bottom: 3px;
}
.search-icon:hover {
    color: #1890ff;
}
.supervise-search-icon:hover {
    color: #1890ff;
}
/deep/ .ant-select-open .ant-select-arrow-icon svg {
    transform: rotate(0deg);
    transition: transform 0s;
}
/deep/ .ant-input {
    padding-right: 40px;
}
/deep/ .ant-select-selection__rendered {
    margin-right: 40px;
}
/deep/ .ant-cascader-picker-label {
    padding-right: 40px;
}
/deep/ .ant-select-selection__clear,
/deep/.ant-cascader-picker-clear {
    right: 28px;
}
</style>
